package com.apexsoft.monitor.mq;

import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.utils.DateUtil;
import com.apexsoft.front.common.utils.SpringContextUtil;
import com.apexsoft.monitor.front.console.log.dao.LogDao;
import com.apexsoft.monitor.front.console.log.om.Log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class LogMqDataConverter implements Runnable {

    private final static Logger log = LogManager.getRootLogger();

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                if (!LogMqSubscribe.queue.isEmpty()) {
                    List<Log> logList = new ArrayList<>();
                    for(int i=0;i<100;i++){
                        if (LogMqSubscribe.queue.isEmpty()) break;

                        String message = LogMqSubscribe.queue.poll();
                        JSONObject jsonObject = JSONObject.parseObject(message);
                        Log l = new Log();
                        l.setAppCode(jsonObject.getString("app_code"));
                        l.setNodeCode(jsonObject.getString("node_code"));
                        l.setLevel(jsonObject.getString("level"));
                        l.setLogFile(jsonObject.getString("log_file"));
                        l.setDate(DateUtil.getNowDate10());
                        l.setTime(DateUtil.getF_TIME8());
                        l.setContent(jsonObject.getString("content"));
                        logList.add(l);
                    }
                    if (logList.size()>0){
                        LogDao logDao = (LogDao) SpringContextUtil.getBean("logDao");
                        logDao.insertBatch(logList);
                        log.debug("发送线程完成："+logList.size());
                    }

                }else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.debug("发送线程出现异常:"+e.getMessage());
            }
        }
    }

}
